package oss

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"xlq-demo/library/config"
	"bytes"
)

type Config struct {
	Endpoint        string
	AccessKeyId     string
	AccessKeySecret string
	Bucket          string
	HostUrl string
}

var ossConfig *Config

func Initial() {
	ossConfig = &Config{
		Endpoint: config.Config.Oss.Endpoint,
		AccessKeyId: config.Config.Oss.AccessKeyId,
		AccessKeySecret: config.Config.Oss.AccessKeySecret,
		Bucket: config.Config.Oss.Bucket,
		HostUrl: config.Config.Oss.Url,
	}
}

//本地文件地址 文件名 文件路径
func PutFile(localFile string, toFile string, path string) (string, error) {
	client, err := oss.New(ossConfig.Endpoint, ossConfig.AccessKeyId, ossConfig.AccessKeySecret)
	if err != nil {
		return "", err
	}

	bucket, err := client.Bucket(ossConfig.Bucket)
	if err != nil {
		return "", err
	}

	err = bucket.PutObjectFromFile(path + "/" + toFile, localFile)
	if err != nil {
		return "", err
	}

	fullPath := ossConfig.HostUrl + "/" + path + "/" + toFile
	return fullPath, nil
}

//上传文本到oss
func PutContent(toFile string, content []byte) (string,error) {
	client, err := oss.New(ossConfig.Endpoint, ossConfig.AccessKeyId, ossConfig.AccessKeySecret)
	if err != nil {
		return "", err
	}

	bucket, err := client.Bucket(ossConfig.Bucket)
	if err != nil {
		return "", err
	}

	err = bucket.PutObject(toFile,bytes.NewReader(content))
	if err != nil {
		return "", err
	}

	fullPath := ossConfig.HostUrl + "/" + toFile
	return fullPath, nil
}
